from django.core.cache import cache
from django.conf import settings


class CaptchaService:
    """
    验证码服务类
    """

    # 生成验证码
    def captcha(self, uuid):
        # 导入图片验证码包
        from lib.captcha.captcha import captcha
        # 生成图片验证码
        text, image = captcha.generate_captcha()
        # 存缓存
        cache.set(uuid, text, settings.CAPTCHA_TIMEOUT*3600)
        # 返回图片验证码 图片二进制
        return {"text": text, "image": image}

    # 验证验证码
    def checkCaptcha(self, text, uuid):
        # 没传验证码
        if not text: return False
        # 没传uuid
        if not uuid: return False
        # 检查验证码是否还在
        c = cache.get(uuid)
        if not c: return False
        # 检查验证码是否相等
        if text != c: return False
        return True